import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/models/goods/goods_obj.dart';
import 'package:xws/models/user/user_obj.dart';
import 'package:xws/res/icons.dart';
import 'package:xws/state/user_state.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/dio_utils/request/goods_req.dart';
import 'package:xws/utils/dio_utils/request/user_req.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/app_img.dart';
import 'package:xws/widgets/app_list_tile.dart';
import 'package:xws/widgets/get_size.dart';
import 'package:xws/widgets/goods_config/goods_item.dart';
import 'package:xws/widgets/refresh_widget/refresh_load_view.dart';
import 'package:xws/widgets/safe_scaffold.dart';
import 'package:xws/widgets/sticky_delegate.dart';

import 'report_page.dart';

/// 其他人主页
class OthersPage extends StatefulWidget {
  const OthersPage({
    Key? key,
    required this.user,
    this.tapFollow,
  }) : super(key: key);

  @override
  _OthersPageState createState() => _OthersPageState();

  final User user;

  final Future<void> Function()? tapFollow;
}

class _OthersPageState extends State<OthersPage> with SafeState<OthersPage> {
  User get _u => widget.user;

  bool get _isMe => us.info.id == _u.id;

  bool get _follow => widget.user.friendFlag;

  double _boxHeight = 200;

  Future<void> _tapFollow() async {
    if (!checkUserLogin) return;

    await widget.tapFollow?.call();
    safeSetState(() {});
  }

  /// 更多操作
  Future<void> _more() async {
    final int? r = await showOptions<int>(
      context,
      options: const <String>['举报', '拉黑'],
    );
    if (r == null) return;

    if (!checkUserLogin) return;

    if (r == 0) push(context, ReportPage(reportType: ReportType.USER, id: _u.id));
    if (r == 1) _blackout();
  }

  /// 拉黑
  Future<void> _blackout() async {
    if (!checkUserLogin) return;

    loading(context);
    final bool r = await blackUser(_u.id);
    close(context);

    if (r) {
      st('拉黑成功', const Duration(seconds: 2));

      close(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeScaffold(
      titleText: '用户详情',
      actions: <Widget>[
        AppBtn.center(
          onTap: _more,
          width: 36,
          height: 36,
          padding: EdgeInsets.zero,
          child: Icon(IR.report, size: 18, color: black(context)),
          color: Colors.transparent,
        ),
      ],
      body: NestedScrollView(
        floatHeaderSlivers: true,
        headerSliverBuilder: (_, __) {
          return <Widget>[_buildUser];
        },
        body: _goods,
      ),
    );
  }

  /// 构建用户块
  Widget get _buildUser {
    return SliverPersistentHeader(
      floating: true,
      delegate: StickyDelegate(
        maxHeight: _boxHeight,
        child: ColoredBox(
          color: white(context),
          child: GetSize(
            onChange: (Size s) {
              safeSetState(() => _boxHeight = s.height);
            },
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                AppListTile(
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                  leading: Padding(
                    padding: const EdgeInsets.only(right: 10),
                    child: Stack(
                      alignment: Alignment.bottomRight,
                      children: <Widget>[
                        AppImg.fitCover(
                          url: _u.avatarUrl,
                          width: 64,
                          height: 64,
                          radius: 10,
                        ),
                        Container(
                          width: 16,
                          height: 16,
                          child: Icon(
                            _u.gender == '男' ? IR.male : IR.fmale,
                            size: 10,
                            color: theme(context),
                          ),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: white(context),
                            borderRadius: const BorderRadius.only(topLeft: Radius.circular(10)),
                          ),
                        ),
                      ],
                    ),
                  ),
                  title: Padding(
                    padding: const EdgeInsets.only(bottom: 8),
                    child: Text(
                      _u.nickName,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  subtitle: Row(
                    children: <Widget>[
                      const Icon(Icons.location_on_rounded, size: 14),
                      const SizedBox(width: 4),
                      Text(
                        _u.city + ' ' + _u.region,
                        style: const TextStyle(fontSize: 14),
                      ),
                    ],
                  ),
                  trailing: _isMe
                      ? null
                      : Padding(
                          padding: const EdgeInsets.only(left: 6),
                          child: AppBtn(
                            onTap: _tapFollow,
                            height: 28,
                            radius: 14,
                            padding: const EdgeInsets.symmetric(horizontal: 12),
                            color: _follow ? theme(context) : white(context),
                            border: Border.all(color: black(context).withOpacity(_follow ? 0 : 0.5), width: 0.5),
                            child: Row(
                              children: <Widget>[
                                Icon(
                                  _follow ? Icons.check_rounded : Icons.add_rounded,
                                  size: 15,
                                  color: _follow ? white(context) : black(context),
                                ),
                                const SizedBox(width: 2),
                                Text(
                                  _follow ? '已关注' : '关注',
                                  maxLines: 1,
                                  style: TextStyle(
                                    fontSize: 11,
                                    color: _follow ? white(context) : black(context),
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 20, top: 10),
                  child: Text(
                    '个人简介:',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 13,
                      color: theme(context),
                    ),
                  ),
                ),
                Flexible(
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.only(left: 20, top: 4, bottom: 20),
                    child: Text(
                      _u.description,
                      style: const TextStyle(fontSize: 12),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 物品
  Widget get _goods {
    return RefreshLoadView<GoodsObj>(
      type: ViewType.waterfall,
      padding: const EdgeInsets.all(20),
      itemBuilder: (int index, GoodsObj v) => GoodsItem(
        index: index,
        goodsObj: v,
        fromUser: true,
      ),
      onRefresh: (_, __) async => await getGoodsList(pageNum: 1, userId: _u.id),
      onLoad: (int page, __) async {
        return getGoodsList(pageNum: page, userId: _u.id);
      },
    );
  }
}
